<?php

namespace Common;


class APP
{
    public $base_dir;
    protected static $instance;

    public $config;

    protected function __construct($base_dir = '')
    {
        $this->base_dir = $base_dir;
        $this->config = new Config(BASEDIR . $base_dir . '/configs');
    }

    public static function getInstance($base_dir = '')
    {
        if (empty(self::$instance)) {
            self::$instance = new self($base_dir);
        }
        return self::$instance;
    }

    public function run()
    {
        $uri = $_SERVER['REQUEST_URI'];
        //  $c 控制器,$a 方法
        list($c, $a) = explode('/', ltrim($uri, '/'));
        // 全小写
        $c_low = strtolower($c);
        // 首字母大写
        $c = ucwords($c);
        $class = '\\APP\\Controller\\' . $c;
        // 加载请求类
        $obj = new $class($c, $a);

        // 读取装饰器配置类
        $controller_config = $this->config['controller'];

        // 获取所有的装饰
        $decorators = array();
        if (isset($controller_config[$c_low]['decorator'])) {
            $conf_decorator = $controller_config[$c_low]['decorator'];
            foreach ($conf_decorator as $class) {
                $decorators[] = new $class;
            }
        }

        // 装饰器前调用的方法
        foreach ($decorators as $decorator) {
            $decorator->beforeRequest($obj);
        }
        // 执行具体的方法
        $return_value = $obj->$a();
        // 装饰器后调用的方法
        foreach ($decorators as $decorator) {
            $decorator->afterRequest($return_value);
        }
    }
}
